package org.example.controller;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.example.datasource.DataSourceManager;
import org.example.datasource.SubjectContext;
import org.example.mapper.DynamicSqlMapper;
import org.example.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/query")
public class QueryController {

    @Autowired
    private DynamicSqlMapper dynamicSqlMapper;

    @Autowired
    private DataSourceManager dataSourceManager;

    @PostMapping("/executeQuery")
    public List<Map<String, Object>> executeQuery(@RequestBody QueryRequest query) {

        try {
            //缓存数据源
            dataSourceManager.loadDataSource(query.subjectId);

            //数据源key
            SubjectContext.setDataSourceKey(CommonUtils.getDsKey(query.subjectId));

            return dynamicSqlMapper.executeQuery(query.getSql());

        } finally {
            SubjectContext.clear();
        }

    }

    @PostMapping("/getTableMetaData")
    public List<Map<String, Object>> getTableMetaData(@RequestBody QueryRequest query) {

        try {
            //缓存数据源
            dataSourceManager.loadDataSource(query.subjectId);

            //数据源key
            SubjectContext.setDataSourceKey(CommonUtils.getDsKey(query.subjectId));

            return dynamicSqlMapper.getTableMetaData("jshop_brand");

        } finally {
            SubjectContext.clear();
        }

    }

    @Data
    public static class QueryRequest {
        private String sql;
        public Long subjectId;
    }

}
